<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="请输入关键字" style="width: 200px;" class="filter-item" size="mini" round @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" size="mini" style="margin-left: 10px;" round @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData">
        批量删除
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="skip">
        学生页面
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="77" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.teacherName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工号" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.teacherId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete (row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" placeholder="输入11位有效的手机号" />
        </el-form-item>
        <el-form-item label="姓名" prop="teacherName">
          <el-input v-model="temp.teacherName" placeholder="输入1-20位中英文姓名" />
        </el-form-item>
        <el-form-item label="工号" prop="teacherId">
          <el-input v-model="temp.teacherId" placeholder="输入1-20位纯数字学号" />
        </el-form-item>
        <el-form-item label="角色" prop="type">
          <el-select v-model="temp.type" placeholder="角色" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in typeoption" :key="item" :label="item" :value="item" />
          </el-select>
          <el-form-item label="是否操作监控" prop="isOperatemonitor">
            <el-select v-model="temp.isOperatemonitor" placeholder="请选择是或否" clearable style="width: 120px" class="filter-item">
              <el-option v-for="item in isOperatemonitoroption" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTeacherList, addteacherList, deleteteacherList, deleteteachetLists, updateteacherList } from '@/api/teacher'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { isPhone, isName, isStunum } from '@/utils/validate'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      sels: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: ''
      },
      isOperatemonitoroption: ['是', '否'],
      typeoption: ['admin'],
      temp: {
        // title:'',
        // num:'',
        item: [],
        teacherId: '',
        teacherName: '',
        phoneNumber: '',
        type: '',
        isOperatemonitor: '',
        password: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑教师',
        create: '新增教师'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        title: [{ required: true, message: '姓名不能为空', trigger: 'blur' },
          { type: 'string', max: 20, message: '姓名不能大于20位', trigger: 'blur' },
          { validator: isName, trigger: 'blur' }
        ],
        phonenum: [{ required: true, message: '手机号不可为空', trigger: 'blur' },
          // { type: 'string', min: 11, message: '手机号不允许小于11位', trigger: 'blur' },
          { validator: isPhone, trigger: 'blur' }],
        teachernum: [{ required: true, message: '工号不能为空', trigger: 'blur' },
          { type: 'string', max: 20, message: '工号不能大于20位', trigger: 'blur' },
          { validator: isStunum, trigger: 'blur' }]

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    skip() {
      this.$router.push('/setting/index/5/userManagement')
    },
    getList() {
      this.listLoading = true
      getTeacherList(this.listQuery).then(res => {
        this.list = res.data.records
        this.total = res.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    selectRow(sels) {
      this.sels = sels
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        for (let i = 0; i < this.sels.length; i++) {
          this.temp.item[i] = this.sels[i].teacherId
        }
        deleteteachetLists(this.temp)
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    },
    resetTemp() {
      this.temp = {
        item: [],
        teacherId: '',
        teacherName: '',
        phoneNumber: '',
        type: '',
        isOperatemonitor: '',
        password: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.password = '123456'
          addteacherList(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateteacherList(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row)
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteteacherList(row)
        this.getList()
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    }
  }
}
</script>
